package org.readme.web;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.readme.mapper.LoginUserMapper;
import org.readme.pojo.LoginUser;
import org.readme.util.SqlSessionFactoryUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        System.out.println("registerServlet_doGet?");
        //接收用户数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(username);
        loginUser.setPassword(password);

        //根据用户名查询用户对象
        /*String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);*/
        //使用工具类
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        LoginUserMapper loginUserMapper = sqlSession.getMapper(LoginUserMapper.class);
        LoginUser loginUser1 = loginUserMapper.selectByUsername(username);

        PrintWriter writer = resp.getWriter();
        //判断用户名是否存在
        if (loginUser1 == null) {
            //用户不存在，添加用户
            loginUserMapper.add(loginUser);
            sqlSession.commit();
            System.out.println("添加成功");
            writer.write("注册成功");
        } else {
            //提示信息
            System.out.println("用户已存在，注册失败" + loginUser1);
            writer.write("用户已存在，注册失败");
        }

        sqlSession.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("registerServlet_doPost?");
        this.doGet(req, resp);
    }
}
